import md5 from 'js-md5';
import Vue from 'vue'
// js精确加法运算
export function accAdd(arg1, arg2) {
    var r1, r2, m, c;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    c = Math.abs(r1 - r2);
    m = Math.pow(10, Math.max(r1, r2));
    if (c > 0) {
        var cm = Math.pow(10, c);
        if (r1 > r2) {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", "")) * cm;
        } else {
            arg1 = Number(arg1.toString().replace(".", "")) * cm;
            arg2 = Number(arg2.toString().replace(".", ""));
        }
    } else {
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", ""));
    }
    return (arg1 + arg2) / m;
};
// js精确乘法运算
export function floatMul(arg1, arg2) {
    var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length
    } catch (e) {}
    try {
        m += s2.split(".")[1].length
    } catch (e) {}
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
};
// 处理要md5加密的数据
export function dictionaryOrderWithData(dic) {
    var result = "";
    var sdic = Object.keys(dic).sort(function(a, b) {
        return a.localeCompare(b)
    });
    var value = "";

    for (var ki in sdic) {
        if (dic[sdic[ki]] == null) {
            value = ""
        } else {
            if (typeof dic[sdic[ki]] == 'object') {
                value = JSON.stringify(dic[sdic[ki]]);
            } else {
                value = dic[sdic[ki]];
            }
        }
        result += sdic[ki] + value;
    }

    return result.replace(/\s/g, "");
};
// 获取到加密之后的数据
export function getMD5Staff(queryData, timestamp, nonce) {
    let data = '';
    if (typeof queryData == "object" && queryData instanceof Object) {
        data = dictionaryOrderWithData(queryData);
    }
    return md5(timestamp + nonce + data);
}
// 把MD5加密的数据放在header里
export function addMd5toHeader(request, token) {
    let timestamp = (new Date()).getTime();
    let nonce = Math.random().toString(36).substring(2);
    // token
    request.headers.token = token;
    // 时间戳
    request.headers.timestamp = timestamp;
    // 随机字符串
    request.headers.nonce = nonce;
    // 签名
    request.headers.signature = getMD5Staff(request.data, timestamp, nonce);
    return request
}
// 按钮节流
export function throttle(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
        gapTime = 3000
    }
    let _lastTime = null
    return function() {
        let _nowTime = +new Date()
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            fn.apply(this, arguments) //将this和参数传给原函数
            _lastTime = _nowTime
        }
    }
}
// 加密数据
function encrypt(tokenKey) {
    let timestamp = new Date().getTime();
    let nonce = Math.random()
        .toString(36)
        .substring(2);
    return {
        token: Storage.getStorage(tokenKey),
        timestamp: timestamp,
        nonce: nonce,
        signature: getMD5Staff({}, timestamp, nonce)
    };
}

// 获取url里的参数
export function getUrlKey(name, url) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ''])[1].replace(
        /\+/g, '%20')) || null
}
// 个位数前面加0
export function formate(num) {
    if (num >= 10) {
        return num;
    } else {
        return `0${num}`;
    }
}
// 保留小数后几位
export function toFixed(input, num) {
    return Number(input).toFixed(num)
}
// 千位分隔符
export function thousandBitSeparator(num) {
    return num && num.toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
        return $1 + ",";
    });
}

// 上传照片
export function uploadFile(url, tempPath, tokenkey, formData = {}) {
    let promise = new Promise((resolve, reject) => {
        let header = Object.assign({
                'content-type': 'multipart/form-data'
            },
            encrypt(tokenkey)
        );
        const uploadTask = uni.uploadFile({
            url: url,
            filePath: tempPath,
            name: 'file',
            formData: formData,
            header: header,
            success: res => {
                if (res && res.data) {
                    let data = JSON.parse(JSON.parse(JSON.stringify(res.data)));
                    resolve(data)
                } else {
                    reject(res)
                }
            },
            fail: res => {
                reject(res)
            },
        });
    })
    return promise;
}

// 封装Storage
export const Storage = {
    getStorage: function(key) {
        if (uni.getStorageSync(key)) {
            try {
                let data = JSON.parse(uni.getStorageSync(key));
                let currentTime = new Date().getTime();
                if (currentTime - data.expireTime < 0) {
                    return data.val
                } else {
                    console.log('缓存过期');
                    uni.removeStorageSync(key);
                    return ''
                }
            } catch (e) {
                uni.removeStorageSync(key);
            }
        } else {
            return ''
        }
    },
    // expire的单位为分钟
    setStorage: function(key, val, expire) {
        let storageTime = new Date().getTime();
        //默认过期时间为24小时
        let expireTime = expire ? 1000 * 60 * expire : 1000 * 60 * 60 * 24;
        let obj = {};
        obj.expireTime = storageTime + expireTime;
        obj.val = val;
        uni.setStorageSync(key, JSON.stringify(obj));
    },
    removeStorage: function(key) {
        try {
            uni.removeStorageSync(key);
        } catch (e) {
            // error
        }
    },
}
export function deepClone(target) {
    // 定义一个变量
    let result;
    // 如果当前需要深拷贝的是一个对象的话
    if (typeof target === 'object') {
        // 如果是一个数组的话
        if (Array.isArray(target)) {
            result = []; // 将result赋值为一个数组，并且执行遍历
            for (let i in target) {
                // 递归克隆数组中的每一项
                result.push(deepClone(target[i]))
            }
            // 判断如果当前的值是null的话；直接赋值为null
        } else if (target === null) {
            result = null;
            // 判断如果当前的值是一个RegExp对象的话，直接赋值    
        } else if (target.constructor === RegExp) {
            result = target;
        } else {
            // 否则是普通对象，直接for in循环，递归赋值对象的所有值
            result = {};
            for (let i in target) {
                result[i] = deepClone(target[i]);
            }
        }
        // 如果不是对象的话，就是基本数据类型，那么直接赋值
    } else {
        result = target;
    }
    // 返回最终结果
    return result;
}

// 获取月日
export function getMonthAndDay(date) {
    if (date) {
        let _date = new Date(date.replace(/-/g, '/'));
        return formate(_date.getMonth() + 1) + '月' + formate(_date.getDate()) + '日';
    }
}

// 数组拍平
export function flatten(arr, key) {
    return arr.reduce(function(pre, cur) {
        if (!Array.isArray(cur[key])) {
            return [...pre, cur];
        } else {
            return [...pre, ...flatten(cur[key])];
        }
    }, []);
}


